#include <stdlib.h>
#include <stdio.h>
#include <nds.h>

// common headers
#include "common.h"

// local headers

#include "main.h"

#define _VERSION_INT MAKE_VERSION(0, 0, 1, STATE_BETA, 1)
char _VERSION_STR[VERSION_STR_MAX_LEN+1];

// libraries id (zero terminated array)
u32 ids[]={ ID_LIBRARY_CONFIG, 0 };

int init() {
	std->sprintf(_VERSION_STR, VERSION_FORMAT, VERSION_ARGS(_VERSION_INT));	// make version str 0.0.1b1

	return 0;
}

u32 query(u32 query) {
	switch(query) {
	case QUERY_NAME:		// plugin name
		return (u32)"config dumper";
	case QUERY_VERSION_INT:	// plugin integer version
		return (u32)_VERSION_INT;
	case QUERY_VERSION_STR:	// plugin string version
		return (u32)_VERSION_STR;
	case QUERY_AUTHOR:		// plugin author
		return (u32)"Ludo6431";
	case QUERY_IDS:			// libraries id (zero terminated array)
		return (u32)ids;
	case QUERY_FILEEXT:		// file extensions directly handled by the plugin
		return (u32)NULL;
	default:
		return 0;
	}
}

#define WAIT_KEYD(k) \
	do { \
		nds->scanKeys(); \
		while(!(nds->keysDown() & (k))) { \
			nds->scanKeys(); \
			nds->swiWaitForVBlank(); \
		} \
	} while(0)

#define WAIT_KEYDR(k) \
	do { \
		nds->scanKeys(); \
		while(!(nds->keysDownRepeat() & (k))) { \
			nds->scanKeys(); \
			nds->swiWaitForVBlank(); \
		} \
	} while(0)

int main(int argc, char *argv[]) {
    sLibResult libres;
    sLibProc *libcfg;
    sCInterface *CI;

	char *fn=argc==1?argv[0]:"/conf.ini";

	std->iprintf("\x1b[2JDumping config file : %s\n", fn);	// clear screen and print filename

	// get config library
	libcfg=api->newLibInstance((libres=api->getLibraryByFileExt(fn, tCONFIG)).lib);
	if(!libcfg) {
		std->iprintf("Can't open config library !\n");
		return 1;
	}

	CI=(sCInterface *)libcfg->query(QUERY_FSTRUCT);
	if(!CI) {
		std->iprintf("Can't get config library interface !\n");
		api->deleteLibInstance(libcfg);
		return 1;
	}

	FILE *fd=f->open(fn, "rb");
	if(!fd) {
		std->iprintf("Can't open config file\n");
		api->deleteLibInstance(libcfg);
		return 1;
	}

	void *confd=CI->open(fd, libres.extid);
	if(!confd) {
		std->iprintf("Can't load config file\n");
		f->close(fd);
		api->deleteLibInstance(libcfg);
		return 1;
	}

	nds->keysSetRepeat(34, 7);

	char *section, *param, *value;
	if(!CI->get_first(confd, &section, &param, &value))	// get first value
		do {
			std->iprintf("[%s]%s=%s\n", section, param, value);
			std->iprintf("Press A\n");
			WAIT_KEYDR(KEY_A);
			std->iprintf("\x1b[1A       \n\x1b[1A");	// clear space used by "Press A"
		} while(!CI->get_next(confd, &section, &param, &value));	// get next

	CI->close(confd);
	f->close(fd);
	api->deleteLibInstance(libcfg);

	std->iprintf("EOF. Press A to exit\n");
	WAIT_KEYD(KEY_A);

	return 0;
}

void deinit() {
}

